<template>
	<view class="container">
		<view class="main-content-frequency">
			<!-- Option Buttons -->
			<view class="options">
				<view class="options-left">
					<text class="distance">{{ verticalDistance }}</text>
					<text>上下位置</text>
				</view>

				<view ref="dragArea" class="slider-container">
					<!-- angle-bg.png as background -->
					<image src="https://wq.hoeagri.com/static/angle-bg.png" class="bg-image"></image>

					<!-- Up, down, left, right arrows -->
					<image src="/static/angle-up.png" class="points-image up-arrow arrow-up"
						@click="changePosition('up')"></image>
					<image src="/static/angle-down.png" class="points-image down-arrow arrow-down"
						@click="changePosition('down')"></image>
					<image src="/static/angle-left.png" class="points-image left-arrow arrow-left"
						@click="changePosition('left')"></image>
					<image src="/static/angle-right.png" class="points-image right-arrow arrow-right"
						@click="changePosition('right')"></image>

					<!-- Ball (draggable and displays position distance) -->
					<image src="/static/angle-ball.png" class="points-image ball"
						:style="{ top: positionY + 'rpx', left: positionX + 'rpx' }" mode="widthFix"
						@touchstart="onDragStart" @touchmove="onDragMove" @touchend="onDragEnd"></image>
				</view>

				<view class="right-column">
					<view class="options-text">
						<text class="distance">{{ horizontalDistance }}</text>
						<text>左右位置</text>
					</view>
				</view>
			</view>
		</view>

		<!-- Start Button at the bottom right -->
		<view class="start-column-frequency" @click="startGame">
			<button class="start-button">{{ gameStatus === 0 ? '开始' : '结束' }}</button>
			<image src="/static/start.png"></image>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				positionX: 185,
				positionY: 185,
				startX: 0,
				startY: 0,
				dragAreaWidth: 415,
				dragAreaHeight: 415,
				buttonSize: 200,
				stepSize: 5,
				gameStatus: 0, // 游戏状态，0 表示停止，1 表示开始
			};
		},
		onLoad() {
			this.loadFrequencyFromLocal();
		},
		computed: {
			verticalDistance() {
				// this.saveFrequencyToLocal();
				const new_x = Math.round(((4600 - 300) * (300 - this.positionY)) / (300 - 70) + 300);
				return new_x;
			},
			horizontalDistance() {
				// this.saveFrequencyToLocal();
				const new_y = Math.round(((2900 - 600) * (300 - this.positionX)) / (300 - 70) + 600);
				return new_y;
			},
		},
		methods: {
			async startGame() {
				// 获取本地存储的 ctrlMachine
				let ctrlMachine = uni.getStorageSync("ctrlMachine") || {};
							
				// 根据当前游戏状态来切换开始和结束
				if (this.gameStatus === 0) {
				  this.gameStatus = 1;  // 设置为已开始
				  ctrlMachine.gameStatus = 1; // 更新 ctrlMachine 中的状态
				  uni.setStorageSync("ctrlMachine", ctrlMachine); // 保存到本地存储
				} else {
				  this.gameStatus = 0;  // 设置为已结束
				  ctrlMachine.gameStatus = 0; // 更新 ctrlMachine 中的状态
				  uni.setStorageSync("ctrlMachine", ctrlMachine); // 保存到本地存储
				}
				let angleData = uni.getStorageSync("ctrlMachine");
				if (angleData || !angleData.dir) {
					// 等待 saveFrequencyToLocal 完成
					await this.saveFrequencyToLocal();
					// 重新获取更新后的 angleData
					angleData = uni.getStorageSync("ctrlMachine");
				}
				console.log('角度设置请求数据：', angleData);
				this.$api.post({
					url: '/common/startAngleMode',
					loadingTip: '正在设置角度...',
					data: {
						angleData,
					},
					success: (res) => {
					  if (this.gameStatus === 1) {
					    uni.showToast({
					      title: '已开始',
					      icon: 'success',
					    });
					  } else {
					    uni.showToast({
					      title: '已结束',
					      icon: 'success',
					    });
					  }
					},
				});
			},
			saveFrequencyToLocal() {
				return new Promise((resolve, reject) => {
					try {
						let existingData = uni.getStorageSync('ctrlMachine') || {};
						existingData.positionX = Math.round(this.positionX);
						existingData.positionY = Math.round(this.positionY);
						let horizontalValue = this.horizontalDistance.toString().padStart(4, '0');
						let verticalValue = this.verticalDistance.toString().padStart(4, '0');
						existingData.dir = '0x' + horizontalValue + verticalValue;
						uni.setStorageSync('ctrlMachine', existingData);
						resolve();
					} catch (error) {
						reject(error);
					}
				});
			},
			loadFrequencyFromLocal() {
				const storedFrequency = uni.getStorageSync('ctrlMachine');
				if (storedFrequency !== '' && storedFrequency !== undefined) {
					this.positionX = storedFrequency.positionX;
					this.positionY = storedFrequency.positionY;
				}
			},
			changePosition(direction) {
				if (direction === 'up') {
					this.positionY = Math.max(70, this.positionY - this.stepSize);
				} else if (direction === 'down') {
					this.positionY = Math.min(300, this.positionY + this.stepSize);
				} else if (direction === 'left') {
					this.positionX = Math.max(70, this.positionX - this.stepSize);
				} else if (direction === 'right') {
					this.positionX = Math.min(300, this.positionX + this.stepSize);
				}
				this.saveFrequencyToLocal();
			},
			onDragStart(e) {
				this.startX = e.touches[0].clientX - this.positionX;
				this.startY = e.touches[0].clientY - this.positionY;
			},
			onDragMove(e) {
				let newX = e.touches[0].clientX - this.startX;
				let newY = e.touches[0].clientY - this.startY;

				newX = Math.max(this.buttonSize / 2 - 30, Math.min(this.dragAreaWidth - this.buttonSize / 2 - 15, newX));
				newY = Math.max(this.buttonSize / 2 - 30, Math.min(this.dragAreaHeight - this.buttonSize / 2 - 15, newY));
				this.positionX = newX;
				this.positionY = newY;
			},
			onDragEnd() {
				console.log("当前位置：", this.positionX, this.positionY);
				this.saveFrequencyToLocal();
			}
		},
	};
</script>


<style lang="scss" scoped>
	.container {
		display: flex;
		flex-direction: column;
		align-items: center;
		background-color: #000;
		color: #fff;
		width: 100%;
		height: 100vh;
		/* 确保占满视窗高度 */
		overflow: hidden;
		/* 禁止页面滚动 */
		padding-top: env(safe-area-inset-top);
		padding-bottom: env(safe-area-inset-bottom);
		touch-action: none;
		/* 禁止手势引起页面滚动 */
	}

	.main-content-frequency {
		display: flex;
		justify-content: space-between;
		width: 350px;
		margin-bottom: 233px;
	}

	.options {
		display: flex;
		flex-direction: column;
		align-items: flex-start;
		width: 100%;
	}

	.options-left {
		margin: 50px 50px 10px 50px;

		.distance {
			margin-right: 5px;
			padding: 5px;
			width: 73rpx;
			height: 36rpx;
			line-height: 36rpx;
			background: #FFFFFF;
			border-radius: 17rpx;
			color: #65C61D;
		}
	}

	.slider-container {
		margin-top: 21rpx;
		width: 415rpx;
		height: auto;
		aspect-ratio: 1;
		position: relative;

		.arrow-up {
			position: absolute;
			top: 0;
			left: 50%;
			transform: translateX(-50%);
		}

		.arrow-down {
			position: absolute;
			bottom: 0;
			left: 50%;
			transform: translateX(-50%);
		}

		.arrow-left {
			position: absolute;
			left: 0%;
			top: 50%;
			transform: translateY(-50%);
		}

		.arrow-right {
			position: absolute;
			right: 0%;
			top: 50%;
			transform: translateY(-50%);
		}

		.left-arrow,
		.right-arrow {
			width: 40rpx;
			height: 66rpx;
			margin-left: 25rpx;
			margin-right: 25rpx;
		}

		.up-arrow,
		.down-arrow {
			width: 66rpx;
			height: 40rpx;
			margin-top: 25rpx;
			margin-bottom: 25rpx;
		}
	}

	.right-column {
		position: absolute;
		bottom: 478rpx;
		right: 20px;
		display: flex;
		flex-direction: column;
		align-items: center;

		.options-text {
			margin: 10px;
			font-weight: 400;
			font-size: 28rpx;

			.distance {
				margin-right: 5px;
				padding: 5px;
				width: 73rpx;
				height: 36rpx;
				line-height: 36rpx;
				background: #FFFFFF;
				border-radius: 17rpx;
				color: #65C61D;
			}
		}
	}

	.bg-image {
		width: 100%;
		height: 100%;
		position: relative;
	}

	.points-image {
		position: absolute;
		z-index: 10;
		cursor: pointer;
	}

	.ball {
		width: 44rpx;
		height: 44rpx;
	}

	.start-column-frequency {
		position: absolute;
		bottom: 0;
		right: 61rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.start-button {
		width: 100%;
		border-radius: 10px;
		background-color: transparent;
		color: #FFFFFF;
		font-size: 36rpx;
		text-align: center;
		border: none;
		transition: all 0.3s ease;
	}

	.start-button:hover {
		cursor: pointer;
	}

	.start-button:focus {
		outline: none;
	}

	image {
		width: 182rpx;
		height: 182rpx;
	}
</style>